<template>
   <ul class="list">
       <!--touch事件需要小写-->
       <li class="item"
           v-for="item of letters"
           :key="item"
           :ref="item"
           @click="clickAlpha"
           @touchstart = "handleTouchStart"
           @touchmove = "handleTouchMove"
           @touchend = "handleTouchEnd"
       >{{item}}</li>
   </ul>
</template>

<script>
  export default {
    name: 'cityAlphabet',
    props:{
      alpha:Object
    },

    data () {
        return {
          touchStatus:false,
          oTop:0,
          timer:false  //用于函数节流，减少手指触摸的执行次数，提高性能
        }
    },

    updated:function(){
      this.oTop = this.$refs['A'][0].offsetTop;
    },

    computed:{
      letters () {
        const letters = [];
        //i为对象的键值
        for (let i in this.alpha){
          letters.push(i);
        }
        return letters;
      }
    },

    methods:{
      /*实现点击字母列表跟着跳转的功能
      * 1、把点击的字母传给列表（通过父亲传递）
      * 2、列表接受跳转
      * */
      clickAlpha:function (e) {
        let alp = e.target.innerText; //获取点击元素的文本值
        this.$emit('change',alp)
      },

      /*实现滚动字母表列表页跟着滚动
      * 计算当前滚动到的点传值给父亲组件
      * 计算方式：（手指所在处的字母距离顶部的距离 - A字母距离顶部的距离） / 每个字母的高度
      * */

      handleTouchStart () {
        this.touchStatus = true;
      },
      handleTouchMove (e) {
        if(this.timer){
          clearTimeout(this.timer);
        }
        this.timer = setTimeout( () => {
          if(this.touchStatus){
            //每次滚动都会计算oTop,将其搬到updataed生命周期钩子中去计算提高性能
            //let oTop = this.$refs['A'][0].offsetTop;
            let cTop = e.touches[0].clientY - 79; //手机触摸点距离屏幕顶部的高度
            let index = Math.floor((cTop - this.oTop) / 20);
            if(index >= 0 && index <= this.letters.length){
              this.$emit('change',this.letters[index]);
            }
          }
        },16)
      },
      handleTouchEnd () {
        this.touchStatus = false;
      },
    }
  }
</script>

<style lang="stylus"  scoped>
    @import "~assets/style/param.styl"
    .list
        position absolute
        top 1.58rem
        right 0
        bottom 0
        width .4rem
        background res
        display flex
        flex-direction column
        justify-content center
        text-align center
    .item
        line-height .4rem
        text-align center
        color $themeColor
</style>
